package org.ysling.litemall.wx.web;
// Copyright (c) [ysling] [927069313@qq.com]
// [litemall-plus] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//             http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.ysling.litemall.core.system.SystemConfig;
import org.ysling.litemall.core.utils.JacksonUtil;
import org.ysling.litemall.core.utils.response.ResponseUtil;
import org.ysling.litemall.db.domain.*;
import org.ysling.litemall.wx.annotation.LoginUser;
import org.ysling.litemall.wx.service.WxGrouponRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.ysling.litemall.db.service.*;
import org.ysling.litemall.wx.service.WxRewardService;

import java.util.*;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 首页服务
 */
@Slf4j
@RestController
@RequestMapping("/wx/home")
@Validated
public class WxHomeController {

    @Autowired
    private LitemallAdService adService;
    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallCategoryService categoryService;
    @Autowired
    private WxGrouponRuleService wxGrouponService;
    @Autowired
    private LitemallCouponService couponService;
    @Autowired
    private LitemallRewardService rewardService;
    @Autowired
    private WxRewardService wxRewardService;
    @Autowired
    private ThreadPoolExecutor executorService;


    /**
     * 首页数据
     * @param userId 当用户已经登录时，非空。为登录状态为null
     * @return 首页数据
     */
    @GetMapping("/index")
    public Object index(@LoginUser Integer userId) {
        // 广告列表
        FutureTask<List<LitemallAd>> bannerTask = new FutureTask<>(
                ()-> adService.queryIndex());

        // 分类列表
        FutureTask<List<LitemallCategory>> channelTask = new FutureTask<>(
                ()-> categoryService.queryChannel());

        // 优惠券列表
        FutureTask<List<LitemallCoupon>> couponListTask = new FutureTask<>(
                ()-> couponService.queryAvailableList(userId,0, 3));

        // 新品首发
        FutureTask<List<LitemallGoods>> newGoodsListTask = new FutureTask<>(
                ()-> goodsService.queryByNew(0, SystemConfig.getNewLimit()));

        // 热卖专区
        FutureTask<List<LitemallGoods>> hotGoodsListTask = new FutureTask<>(
                ()-> goodsService.queryByHot(0, SystemConfig.getHotLimit()));

        // 首页商品分页
        FutureTask<PageInfo<LitemallGoods>> allGoodsListTask = new FutureTask<>(
                ()-> PageInfo.of(goodsService.queryByAll(0, 20)));

        executorService.submit(bannerTask);
        executorService.submit(channelTask);
        executorService.submit(couponListTask);
        executorService.submit(newGoodsListTask);
        executorService.submit(hotGoodsListTask);
        executorService.submit(allGoodsListTask);

        Map<String, Object> entity = new HashMap<>();
        try {
            entity.put("banner", bannerTask.get());
            entity.put("channel", channelTask.get());
            entity.put("couponList", couponListTask.get());
            entity.put("newGoodsList", newGoodsListTask.get());
            entity.put("hotGoodsList", hotGoodsListTask.get());
            entity.put("allGoodsList", allGoodsListTask.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseUtil.ok(entity);
    }

    /**
     * 判断首页初始化参数是否支持跳转
     * @return
     */
    @PostMapping("/navigate")
    public Object isNavigate(@RequestBody String body) {
        Integer sceneId = JacksonUtil.parseInteger(body, "sceneId");
        String sceneType = JacksonUtil.parseString(body, "sceneType");
        if (sceneId == null || sceneId <= 0 || sceneType == null){
            return ResponseUtil.fail(800,"分享获取失败");
        }
        if (sceneType.equals("goods")){
            LitemallGoods goods = goodsService.findById(sceneId);
            if (goods == null){
                return ResponseUtil.fail(800,"商品不存在");
            }
        }
        if (sceneType.equals("groupon")){
            Object groupon = wxGrouponService.isGroupon(sceneId);
            if (groupon != null){
                return groupon;
            }
        }
        if (sceneType.equals("reward")){
            LitemallReward reward = rewardService.findById(sceneId);
            if (reward == null) {
                return ResponseUtil.fail(800,"活动不存在");
            }

            Object serviceReward = wxRewardService.isReward(reward.getTaskId());
            if (serviceReward != null){
                return serviceReward;
            }
        }
        return ResponseUtil.ok();
    }


    /**
     * 商城介绍信息
     * @return 商城介绍信息
     */
    @GetMapping("/about")
    public Object about() {
        Map<String, Object> about = new HashMap<>();
        about.put("name", SystemConfig.getMallName());
        about.put("address", SystemConfig.getMallAddress());
        about.put("phone", SystemConfig.getMallPhone());
        about.put("qq", SystemConfig.getMallQQ());
        about.put("longitude", SystemConfig.getMallLongitude());
        about.put("latitude", SystemConfig.getMallLatitude());
        return ResponseUtil.ok(about);
    }
}